package com.kritsana.dk.sendpostjson;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends Activity implements OnClickListener {

	TextView tvIsConnected;
	Button btnPost;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		// get reference to the views
		tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
		btnPost = (Button) findViewById(R.id.btnPost);
		
		// check if you are connected or not
		if(isConnected()){
			tvIsConnected.setBackgroundColor(0xFF00CC00);
			tvIsConnected.setText("You are conncted");
        }
		else{
			tvIsConnected.setText("You are NOT conncted");
		}
		
		// add click listener to Button "POST"
		btnPost.setOnClickListener(this);		
	}

	public static <E> String POST(String url){
		String result = "";
		try {
					    
		    String json = "";	    

		    // 3. build jsonObject
		    
		    JSONObject gpsInfoData = new JSONObject();
		    JSONObject fuelInfoData = new JSONObject();
		    JSONObject tempInfoData = new JSONObject();
		    JSONObject inputInfoData = new JSONObject();
		    
		    JSONArray gpsObjectArray = new JSONArray();	
		    JSONArray fuelObjectArray = new JSONArray();
		    JSONArray tempInfoArray = new JSONArray();
		    JSONArray inputInfoArray = new JSONArray();
		    
		    /*GPS*/
		    gpsInfoData.put("latitude", 1.0);
		    gpsInfoData.put("longtitude", 1.0);
		    gpsInfoData.put("accuracy", 1);
		    gpsInfoData.put("altitude", 1.0);
		    gpsInfoData.put("speed", 1);
		    gpsInfoData.put("heading", 1);
		    gpsInfoData.put("odometer", 1.0);
		    gpsInfoData.put("datetime", "0001-01-01T00:00:00");
		    
		    gpsObjectArray.put(gpsInfoData);
		    
		    /*Fuel*/
		    fuelInfoData.put("fuel", 1);
		    fuelInfoData.put("datetime", "0001-01-01T00:00:00");
		    
		    fuelObjectArray.put(fuelInfoData);		    
		    
		    /*Temp*/
		    tempInfoData.put("temperature", 1.0);
		    tempInfoData.put("datetime", "0001-01-01T00:00:00");
		    
		    tempInfoArray.put(tempInfoData);
		    
		    /*Input*/
		    inputInfoData.put("status", "false");
		    inputInfoData.put("datetime", "0001-01-01T00:00:00");
		    
		    inputInfoArray.put(inputInfoData);
		    	   
		    
		    /*SendInfo*/
		    JSONObject sendInfo = new JSONObject();
		    sendInfo.put("sequenceId", "635247057169946402");
		    sendInfo.put("agentId", "0001");
		    sendInfo.put("datetime", "2014-01-07T15:35:16.9946402");
		    
		    
		    sendInfo.put("gpsInfoCount", gpsObjectArray.length());
		    sendInfo.put("gpsInfo", gpsObjectArray);		    
		    sendInfo.put("fuelInfoCount", fuelObjectArray.length());
		    sendInfo.put("fuelInfo", fuelObjectArray);
		    sendInfo.put("tempInfoCount", tempInfoArray.length());
		    sendInfo.put("tempInfo",tempInfoArray);
		    sendInfo.put("inputInfoCount", inputInfoArray.length());
		    sendInfo.put("inputInfo", inputInfoArray);
		    
		    
		    //4. convert JSONObject to JSON to String
		    //json = jsonObject.toString();
		    
		    json = sendInfo.toString();
		    
		    Log.i("JSON ToString",json);
		    
		    
		    //Log.i("GET", GET(url));
		    
		    List<NameValuePair> params = new ArrayList<NameValuePair>();
	    		    
            params.add(new BasicNameValuePair("json", json.toString()));

		    String formServer = getHttpPost(url, params);
		    Log.i("F Server", formServer);
		    
		    DateTime dt = new DateTime();
		    
		    Calendar c = Calendar.getInstance();
	        System.out.println("Current time => "+c.getTime());
	        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	        String formattedDate = df.format(c.getTime());
	        Log.i("DateTime",formattedDate);
		    
		  //  Log.i("Date Time", dt.DateTime());
		    
		
		} catch (Exception e) {
			Log.d("InputStream", e.getLocalizedMessage());
		}
		
		// 11. return result
		return result;
	}
	
	 @Override
		public void onClick(View view) {
		
			switch(view.getId()){
				case R.id.btnPost:
					if(!validate())
						Toast.makeText(getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
					// call AsynTask to perform network operation on separate thread
					//POST("http://localhost:33621/api/location");
					//new HttpAsyncTask().execute("http://192.168.11.94/moscii/getHttpPost.php");
					new HttpAsyncTask().execute("http://192.168.0.46/api/location");
				break;
			}
			
		}
	
    public boolean isConnected(){
    	ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
    	    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
    	    if (networkInfo != null && networkInfo.isConnected()) 
    	    	return true;
    	    else
    	    	return false;	
    }
   
    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {

            return POST(urls[0]);
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
        	Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
       }
    }
	
	
	private boolean validate(){
			return true;	
	}
	
	private static String convertInputStreamToString(InputStream inputStream) throws IOException{
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        String line = "";
        String result = "Data -> ";
        while((line = bufferedReader.readLine()) != null)
            result += line;
        
        inputStream.close();
        
        Log.i("convertInputStreamToString",result);
        return result;
        
    }
	
	public static String getHttpPost(String url,List<NameValuePair> params) {
		StringBuilder str = new StringBuilder();
		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
		
		Log.i("Params", params.toString());
		
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(params));
			HttpResponse response = client.execute(httpPost);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			if (statusCode == 200) { // Status OK
				HttpEntity entity = response.getEntity();
				InputStream content = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(content));
				String line;
				while ((line = reader.readLine()) != null) {
					str.append(line);
				}
				
				Log.i("STR", str.toString());
			} else {
				Log.e("Log", "Failed to download result..");
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return str.toString();
	}

	  
	 public static String GET(String url){
	        InputStream inputStream = null;
	        String result = "";
	        try {
	 
	            // create HttpClient
	            HttpClient httpclient = new DefaultHttpClient();
	 
	            // make GET request to the given URL
	            HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
	 
	            // receive response as inputStream
	            inputStream = httpResponse.getEntity().getContent();
	 
	            // convert inputstream to string
	            if(inputStream != null)
	                result = convertInputStreamToString(inputStream);
	            else
	                result = "Did not work!";
	 
	        } catch (Exception e) {
	            Log.d("InputStream", e.getLocalizedMessage());
	        }
	        Log.i("Resual", result);
	        return result;
	    }
	
}
